import sqlite3
from contextlib import contextmanager
from sqlite3 import Connection, Cursor
from typing import Iterator


class SalesRepo:
    def __init__(self, database_path: str):
        self.database_path = database_path
        self.create_table()

    @contextmanager
    def _connect(self) -> Iterator[Connection]:
        conn = sqlite3.connect(self.database_path)
        yield conn
        conn.close()

    @contextmanager
    def _cursor(self, conn: Connection) -> Iterator[Cursor]:
        cursor = conn.cursor()
        yield cursor
        cursor.close()

    def create_table(self):
        query = """
        CREATE TABLE IF NOT EXISTS processed_sales (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            sale_id TEXT UNIQUE
        )
        """
        with self._connect() as conn:
            conn.execute(query)

    def add_sale(self, sale_id: str):
        query = "INSERT INTO processed_sales (sale_id) VALUES (?)"
        with self._connect() as conn:
            conn.execute(query, (sale_id,))
            conn.commit()

    def is_sale_processed(self, sale_id: str) -> bool:
        query = "SELECT * FROM processed_sales WHERE sale_id = ?"
        with self._connect() as conn, self._cursor(conn) as cursor:
            cursor.execute(query, (sale_id,))
            result = cursor.fetchone()
            return bool(result)
